import json
import requests
from utils.logger import logger

class BaiLianServices:
    BASE_URL = "https://dashscope.aliyuncs.com/api/v1/apps"
    API_KEY = "sk-d672cfc8c54847ce9b3e13879862de8c"
    APPID_DICT = {
        "measure_info": 'efbd83946de041b6aaa8e65623788fa7',
        "dimension": 'a03e2550c0b34c439c84af6216bf6575',
        "condition": 'd97411479667492496121989e4201b44',
        "query_measure_value":'f6dd7d6545714f238fc6f206002d33bf',
    }
    # 检索知识库
    @staticmethod
    def search_knowledge_base(app_name, query):
        """
        检索知识库
        :param query: 查询文本 
        :param top_k: 返回的结果数量
        :return: 检索结果
        """
        logger.info(f"查询百炼知识库:search_knowledge_base")
        logger.info(f"参数:app_name={app_name},query={query}")
        APP_ID = BaiLianServices.APPID_DICT.get(
            {
                "metric":"measure_info",
                "demensoin":"dimension",
                "filter":"condition",
            }[app_name]
        )
        uri = BaiLianServices.BASE_URL + "/" + APP_ID + "/completion"
        headers = {
            "Authorization": f"Bearer {BaiLianServices.API_KEY}",
            "Content-Type": "application/json"
        }
        data = {
            "input": {
                "prompt": query
            }
        }
        try:
            response = requests.post(uri, headers=headers, data=json.dumps(data,ensure_ascii=False))
            print(response.status_code)
            response.raise_for_status()
            result = response.text
            logger.info(f"查询百炼知识库成功")
            return result
        except Exception as e:  
            logger.error(f"查询百炼知识库异常:{e}")
            return None

if __name__ == "__main__":
    result = BaiLianServices.search_knowledge_base("measure_info","上门率")
    print(result)